﻿using AutoOiSystem.Models;
using Microsoft.Xaml.Behaviors.Media;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Xml.Linq;

namespace AutoOiSystem.ViewModels
{
    public class MainViewModel:BaseNotifyPropertyChanged
    {
        System.Timers.Timer timerTxt;//实时监控TextBox数据变化定时器，TextChanged事件会有堆栈异常
        Thread thClear;//延迟清空TextBox
        string TotalCode = string.Empty;
        int ScanLength = 0;
        int DelayTime = 0;
   
        public MainModel mainModel { get; set; }
        public MainViewModel() 
        {
            mainModel = new MainModel();
            mainModel.IsFocus = true;
            //ScanTxt.Focus();
            var tempLength = ConfigurationManager.AppSettings["Length"];
            var tempDelay = ConfigurationManager.AppSettings["DelayTime"];

            if(tempLength!=null)
            ScanLength=int.Parse(tempLength);

            if (tempDelay != null)
                DelayTime =int.Parse(tempDelay);
           
            timerTxt = new System.Timers.Timer();
            timerTxt.Elapsed += new System.Timers.ElapsedEventHandler(timerTxt_Elapsed);
            timerTxt.Interval = 300;
            timerTxt.Enabled = true;

            thClear = new Thread(new ThreadStart(CheckThread));
           
        }


        #region 定时器扫码
        void timerTxt_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                if (mainModel.AreaId == 1)//AP
                {
                    if (mainModel.ScanText != "" && mainModel.ScanText != null && mainModel.ScanText.Length > ScanLength)// && CodeTxt.Text.Length > 85
                    {
                        try
                        {
                            if (thClear.ThreadState == ThreadState.Unstarted)
                                thClear.Start();
                            else if (thClear.ThreadState == ThreadState.Stopped)
                            {
                                thClear = new Thread(new ThreadStart(CheckThread));
                                thClear.Start();
                            }
                        }
                        catch
                        { }

                    }
                }
                else //LT
                {
                    if (mainModel.ScanText != "" && mainModel.ScanText != null && mainModel.ScanText.Length > 15)// && CodeTxt.Text.Length > 85
                    {
                        try
                        {
                            if (thClear.ThreadState == ThreadState.Unstarted)
                                thClear.Start();
                            else if (thClear.ThreadState == ThreadState.Stopped)
                            {
                                thClear = new Thread(new ThreadStart(CheckThread));
                                thClear.Start();
                            }
                        }
                        catch
                        { }

                    }
                }
            }
            catch (Exception ex)
            {
                
            }
        }


        void CheckThread()
        {

            Thread.Sleep(DelayTime);
            TotalCode = mainModel.ScanText;
            mainModel.ScanText = string.Empty;

            if (mainModel.AreaId == 1)
            {
                if (TotalCode.Length > ScanLength)
                {
                    string TempCode = TotalCode.Remove(TotalCode.Length - ScanLength);//AP从后往前截取

                    mainModel.LogText += DateTime.Now.ToString() + "：" + TempCode + "扫码成功" + TotalCode + "\r\n";

                    //AppendTxt(DateTime.Now.ToString() + "：" + TempCode + "扫码成功" + TotalCode + "\r\n");

                    HandleCode(TempCode);
                }
            }
            else
            {
                string TempCode = TotalCode.Substring(0, 10);//LT截取10位

                mainModel.LogText += DateTime.Now.ToString() + "：" + TempCode + "扫码成功" + TotalCode + "\r\n";

                //AppendTxt(DateTime.Now.ToString() + "：" + TempCode + "扫码成功" + TotalCode + "\r\n");

                HandleCode(TempCode);
            }

            //mainModel.IsFocus = false;
            mainModel.IsFocus = true;

            //ScanTxt.Focus();

        }


        void HandleCode(string ScanCode)
        {
            if (ScanCode != null && ScanCode != "")
            {
                #region 机种码少于10位
                if (ScanCode.Length < 10)//机种码少于10位，则必定是全部机种名
                {
                    System.IO.DirectoryInfo DI = new System.IO.DirectoryInfo(mainModel.oiPath + "\\" + ScanCode);
                    System.IO.FileInfo[] FileArrayAll = null;
                    try
                    { FileArrayAll = DI.GetFiles(); }
                    catch
                    {
                        mainModel.LogText += DateTime.Now.ToString() + "：" + "机种名不正确，服务器查询不到" + "\r\n";
                        //AppendTxt(DateTime.Now.ToString() + "：" + "机种名不正确，服务器查询不到" + "\r\n");
                        MessageBox.Show("机种名不正确，服务器查询不到", "异常", MessageBoxButton.OK, MessageBoxImage.Information);
                        return;
                    }




                    if (FileArrayAll.Length > 0)
                    {
                        List<System.IO.FileInfo> FileList = new List<System.IO.FileInfo>();

                        foreach (System.IO.FileInfo item in FileArrayAll)
                        {
                            if (item.Name.ToLower().EndsWith(".pdf") || item.Name.ToLower().EndsWith(".xls") || item.Name.ToLower().EndsWith(".xlsx"))
                            {
                                FileList.Add(item);
                            }


                        }


                        if (FileList.Count > 0)
                        {
                            int count = 0;
                            for (int i = 0; i < FileList.Count; i++)
                            {
                               
                                if (mainModel.SelectedItem == "Main")
                                {
                                    if (!FileList[i].Name.ToUpper().Contains("(")&& !FileList[i].Name.ToUpper().Contains(")"))
                                    {
                                        OpenPath(FileList[i].FullName);
                                        count++;
                                        mainModel.LogText += DateTime.Now.ToString() + "：" + "打开文档" + FileList[i].Name + "\r\n";
                                        //AppendTxt(DateTime.Now.ToString() + "：" + "打开文档" + FileList[i].Name + "\r\n");

                                        break;
                                    }
                                }
                                else if (mainModel.SelectedItem == "Others")
                                {
                                    OpenPath(mainModel.oiPath + "\\" + ScanCode);
                                    count++;
                                    mainModel.LogText += DateTime.Now.ToString() + "：" + "打开文件夹" + ScanCode + "\r\n";
                                    break;


                                }
                                else
                                {
                                    if (FileList[i].Name.ToUpper().Contains("("+mainModel.SelectedItem.ToUpper()+ ")"))
                                    {
                                        OpenPath(FileList[i].FullName);
                                        count++;
                                        mainModel.LogText += DateTime.Now.ToString() + "：" + "打开文档" + FileList[i].Name + "\r\n";
                                        //AppendTxt(DateTime.Now.ToString() + "：" + "打开文档" + FileList[i].Name + "\r\n");

                                        break;
                                    }

                  
                                }
                            }

                            if (count == 0)
                            {
                                mainModel.LogText += DateTime.Now.ToString() + "：" + "文件不存在" + "\r\n";
                                //AppendTxt(DateTime.Now.ToString() + "：" + "文件不存在" + "\r\n");
                                MessageBox.Show("文件不存在", "异常", MessageBoxButton.OK, MessageBoxImage.Information);
                            }
                        }
                        else
                        {
                            mainModel.LogText += DateTime.Now.ToString() + "：" + "文件不存在" + "\r\n";
                            //AppendTxt(DateTime.Now.ToString() + "：" + "文件不存在" + "\r\n");
                            MessageBox.Show("文件不存在", "异常", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                    }
                    else
                    {
                        mainModel.LogText += DateTime.Now.ToString() + "：" + "文件夹中没有文件" + "\r\n";
                        //AppendTxt();
                        MessageBox.Show("文件夹中没有文件", "异常", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
                #endregion

                #region 机种码大于等于10位
                else
                {
                    System.IO.DirectoryInfo DiBox = new System.IO.DirectoryInfo(mainModel.oiPath);
                    System.IO.DirectoryInfo[] DirArrayAll = null;

                    try
                    { DirArrayAll = DiBox.GetDirectories(); }
                    catch
                    {
                        mainModel.LogText += DateTime.Now.ToString() + "：" + "机种名不正确，服务器查询不到" + "\r\n";
                        //AppendTxt(DateTime.Now.ToString() + "：" + "机种名不正确，服务器查询不到" + "\r\n");
                        MessageBox.Show("机种名不正确，服务器查询不到", "异常", MessageBoxButton.OK, MessageBoxImage.Information);
                        return;
                    }

                    int tempCount = 0;
                    foreach (System.IO.DirectoryInfo di in DirArrayAll)
                    {
                        if (di.Name.ToUpper().Contains(ScanCode.ToUpper()))
                        {
                            tempCount++;
                            System.IO.DirectoryInfo DI = new System.IO.DirectoryInfo(mainModel.oiPath + "\\" + di.Name);
                            System.IO.FileInfo[] FileArrayAll = DI.GetFiles();

                            List<System.IO.FileInfo> FileList = new List<System.IO.FileInfo>();

                            if (FileArrayAll.Length > 0)
                            {
                                foreach (System.IO.FileInfo item in FileArrayAll)
                                {
                                    if (item.Name.ToLower().EndsWith(".pdf") || item.Name.ToLower().EndsWith(".xls") || item.Name.ToLower().EndsWith(".xlsx"))
                                    {
                                        FileList.Add(item);
                                    }


                                }


                                if (FileList.Count > 0)
                                {
                                    int count = 0;
                                    for (int i = 0; i < FileList.Count; i++)
                                    {
                                        if (mainModel.SelectedItem == "Main")
                                        {
                                            if (!FileList[i].Name.ToUpper().Contains("(") && !FileList[i].Name.ToUpper().Contains(")"))
                                            {
                                                OpenPath(FileList[i].FullName);
                                                count++;
                                                mainModel.LogText += DateTime.Now.ToString() + "：" + "打开文档" + FileList[i].Name + "\r\n";
                                                //AppendTxt(DateTime.Now.ToString() + "：" + "打开文档" + FileList[i].Name + "\r\n");

                                                break;
                                            }
                                        }
                                       
                                        else if (mainModel.SelectedItem == "Others")
                                        {
                                            OpenPath(mainModel.oiPath + "\\" + di.Name);
                                            count++;
                                            mainModel.LogText += DateTime.Now.ToString() + "：" + "打开文件夹" + di.Name + "\r\n";
                                            break;

                                          
                                        }
                                        else
                                        {
                                            if (FileList[i].Name.ToUpper().Contains("(" + mainModel.SelectedItem.ToUpper() + ")"))
                                            {
                                                OpenPath(FileList[i].FullName);
                                                count++;
                                                mainModel.LogText += DateTime.Now.ToString() + "：" + "打开文档" + FileList[i].Name + "\r\n";
                                                //AppendTxt(DateTime.Now.ToString() + "：" + "打开文档" + FileList[i].Name + "\r\n");

                                                break;
                                            }
                                        }
                                    }

                                    if (count == 0)
                                    {
                                        mainModel.LogText += DateTime.Now.ToString() + "：" + "文件不存在" + "\r\n";
                                        MessageBox.Show("文件不存在", "异常", MessageBoxButton.OK, MessageBoxImage.Information);
                                    }
                                }
                                else
                                {
                                    mainModel.LogText += DateTime.Now.ToString() + "：" + "文件不存在" + "\r\n";
                                   // AppendTxt(DateTime.Now.ToString() + "：" + "文件不存在" + "\r\n");
                                    MessageBox.Show("文件不存在", "异常", MessageBoxButton.OK, MessageBoxImage.Information);
                                }
                            }
                            else
                            {
                                mainModel.LogText += DateTime.Now.ToString() + "：" + "文件夹中没有文件" + "\r\n";
                                //AppendTxt();
                                MessageBox.Show("文件夹中没有文件", "异常", MessageBoxButton.OK, MessageBoxImage.Information);
                            }

                            break;
                        }
                    }

                    if (tempCount == 0)
                    {
                        mainModel.LogText += DateTime.Now.ToString() + "：" + "扫码不匹配" + "\r\n";
                        //AppendTxt();
                        MessageBox.Show("扫码不匹配", "异常", MessageBoxButton.OK, MessageBoxImage.Information);
                    }

                }
                #endregion
            }

            //mainModel.IsFocus = false;
            mainModel.IsFocus = true;
            //ScanTxt.Focus();
        }



        void OpenPath(string path)
        {
           //.net core不能直接调用路径
           System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo{FileName = path, UseShellExecute = true });         
        }
        #endregion

        #region Command      
        public ICommand HyperlinkCommand
        {
            get
            {
                return new RelayCommand(
                (param) =>
                {
                    hyperlink_Click(param);
                }
                , (v) => { return true; });
            }
            set { RaisePropertyChanged("HyperlinkCommand"); }
        }


        private void hyperlink_Click(object param)
        {
            try
            {

                OpenPath(mainModel.oiPath);

                //mainModel.IsFocus = false;
                mainModel.IsFocus = true;
                //mainModel.IsFocus = true;
                //ScanTxt.Focus();
            }
            catch
            { MessageBox.Show("服务器打开异常", "异常", MessageBoxButton.OK, MessageBoxImage.Information); }
        }



        public ICommand ScanButtonCommand
        {
            get
            {
                return new RelayCommand(
                (param) =>
                {
                    scanButton_Click(param);
                }
                , (v) => { return true; });
            }
            set { RaisePropertyChanged("ScanButtonCommand"); }
        }


        private void scanButton_Click(object param)
        {
            try
            {
               
                //WindowManager.Register<ScanWindow>("ScanWindow");
                //WindowManager.Show("ScanWindow", null);
                //ScanTxt.Focus();
                ScanWindow sw = new ScanWindow();              
                ScanViewModel svm = new ScanViewModel();
                svm.HandEvent += Svm_HandEvent;
                sw.DataContext = svm;
                sw.ShowDialog();



                //mainModel.IsFocus = false;
                mainModel.IsFocus = true;
            }
            catch
            {  }
        }

        private void Svm_HandEvent(string text)
        {
            string str = string.Empty;
            for (int i = 0; i < ScanLength; i++)
            {
                str += "-";
            }


            mainModel.ScanText = text+str;
        }


        #endregion
    }
}
